<template>
    <div class="login">
      <!-- 登录方式切换 -->
      <div class="login-type">
        <div class="type-item" :class="{ active: loginType === 'sms' }" @click="loginType = 'sms'">
          短信登录
        </div>
        <div class="type-item" :class="{ active: loginType === 'password' }" @click="loginType = 'password'">
          密码登录
        </div>
      </div>
      <!-- 短信登录表单 -->
      <van-form @submit="onLogin" v-if="loginType === 'sms'">
        <van-field v-model="mobile" name="mobile" label="手机号" placeholder="请输入手机号" :rules="[{ required: true, message: '请填写手机号' }]"/>
        <van-field v-model="imageCode" name="imageCode" label="图形验证码" placeholder="请输入图形验证码" :rules="[{ required: true, message: '请填写图形验证码' }]">
          <template #button>
            <img :src="imageCodeUrl" @click="getImageCode" style="height: 32px; cursor: pointer" alt="点击刷新验证码"/>
          </template>
        </van-field>
        <van-field v-model="smsCode" name="smsCode" label="短信验证码" placeholder="请输入短信验证码" :rules="[{ required: true, message: '请填写短信验证码' }]">
          <template #button>
            <van-button size="small" type="primary" @click="sendSmsCode" :disabled="smsBtnDisabled">
              {{ smsBtnText }}
            </van-button>
          </template>
        </van-field>
        <div style="margin: 16px;">
          <van-button round block type="primary" native-type="submit">登录</van-button>
        </div>
      </van-form>
      <!-- 密码登录表单 -->
      <van-form @submit="onPasswordLogin" v-else>
        <van-field v-model="username" name="username" label="账号" placeholder="请输入手机号/用户名" :rules="[{ required: true, message: '请填写账号' }]"/>
        <van-field v-model="password" type="password" name="password" label="密码" placeholder="请输入密码" :rules="[{ required: true, message: '请填写密码' }]"/>
        <div style="margin: 16px;">
          <van-button round block type="primary" native-type="submit">登录</van-button>
        </div>
      </van-form>
      <!-- 其他登录方式 -->
      <div class="other-login">
        <div class="divider">
          <span class="divider-text">其他登录方式</span>
        </div>
        <div class="third-party">
          <div class="third-party-item" @click="thirdPartyLogin('dingtalk')">
            <van-icon name="friends-o" size="24" color="#0089ff"/>
            <span>钉钉</span>
          </div>
          <div class="third-party-item" @click="thirdPartyLogin('alipay')">
            <van-icon name="alipay" size="24" color="#1677FF"/>
            <span>支付宝</span>
          </div>
          <div class="third-party-item" @click="thirdPartyLogin('weibo')">
            <van-icon name="weibo" size="24" color="#FF6F32"/>
            <span>微博</span>
          </div>
        </div>
      </div>
    </div>
  </template>
  <script setup>
  import { ref, onMounted } from 'vue'
  import { showToast } from 'vant'
  import { useRouter } from 'vue-router'
  import axios from 'axios'
  const router = useRouter()
  const loginType = ref('sms') // 登录方式：sms-短信登录，password-密码登录
  const mobile = ref('')
  const imageCode = ref('')
  const smsCode = ref('')
  const imageCodeUrl = ref('')
  const smsBtnText = ref('获取验证码')
  const smsBtnDisabled = ref(false)
  const username = ref('')
  const password = ref('')
  let timer = null
  const imageCodeId = ref(generate_uuid())
  // 生成 uuid
  function generate_uuid() {
    let d = new Date().getTime()
    if (window.performance && typeof window.performance.now === "function") {
      d += performance.now()
    }
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      const r = (d + Math.random() * 16) % 16 | 0
      d = Math.floor(d / 16)
      return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16)
    })
  }
  // 获取图形验证码
  function getImageCode() {
    imageCodeUrl.value = `http://localhost:8000/user/get_image_code/?uuid=${imageCodeId.value}&t=${new Date().getTime()}`
  }
  // 发送短信验证码
  async function sendSmsCode() {
    if (!mobile.value || !imageCode.value) {
      showToast('请填写手机号和图形验证码')
      return
    }
    smsBtnDisabled.value = true
    try {
      await axios.post('http://localhost:8000/user/send_verification_code/', {
        mobile: mobile.value,
        image_code: imageCode.value,
        uuid: imageCodeId.value
      })
      showToast('验证码已发送')
      let count = 60
      smsBtnText.value = `${count}s`
      timer = setInterval(() => {
        count--
        smsBtnText.value = `${count}s`
        if (count <= 0) {
          clearInterval(timer)
          smsBtnText.value = '获取验证码'
          smsBtnDisabled.value = false
        }
      }, 1000)
    } catch (e) {
      showToast(e.response?.data?.message || '发送失败')
      smsBtnDisabled.value = false
      smsBtnText.value = '获取验证码'
      getImageCode()
    }
  }
  // 短信验证码登录
  async function onLogin() {
    if (!mobile.value || !smsCode.value) {
      showToast('请填写手机号和验证码')
      return
    }
    try {
      const res = await axios.post('http://localhost:8000/user/login/', {
        mobile: mobile.value,
        sms_code: smsCode.value
      })
      showToast('登录成功')
      localStorage.setItem('token', 'Bearer ' + res.data.data.token)
      localStorage.setItem('userid', res.data.data.userid)
      router.replace('/')
    } catch (e) {
      showToast(e.response?.data?.message || '登录失败')
    }
  }
  // 账号密码登录
  async function onPasswordLogin() {
    if (!username.value || !password.value) {
      showToast('请填写账号和密码')
      return
    }
    try {
      const res = await axios.post('http://localhost:8000/user/password_login/', {
        username: username.value,
        password: password.value
      })
      showToast('登录成功')
      localStorage.setItem('token', 'Bearer ' + res.data.data.token)
      localStorage.setItem('userid', res.data.data.userid)
      router.replace('/')
    } catch (e) {
      showToast(e.response?.data?.message || '登录失败')
    }
  }
  // 第三方登录
  const handleDingTalk = () => {
    window.location.href = 'https://login.dingtalk.com/oauth2/auth?' +
      'redirect_uri=http://localhost:5173/login' +
      '&response_type=code' +
      '&client_id=ding8nfthp9uuysffqlw' +
      '&scope=openid' +
      '&state=dddd' +
      '&prompt=consent'
  }
  function thirdPartyLogin(type) {
    switch (type) {
      case 'dingtalk':
        handleDingTalk()
        break
      case 'alipay':
        showToast('暂未开通支付宝登录')
        break
      case 'weibo':
        showToast('暂未开通微博登录')
        break
    }
  }
  // 初始化验证码
  getImageCode()
  onMounted(async () => {
    // 检查URL是否有code参数（钉钉回调）
    const urlParams = new URLSearchParams(window.location.search)
    const code = urlParams.get('code')
    if (code) {
      try {
        // 调用后端回调接口
        const res = await axios.get(`http://localhost:8000/user/dd/callback/?code=${code}`)
        if (res.data.code === 200) {
          const { token, retoken, userid, username, phone } = res.data.data
          localStorage.setItem('token', 'Bearer ' + token)
          localStorage.setItem('userid', userid)
          showToast('登录成功')
          // 清理URL参数
          window.history.replaceState({}, document.title, window.location.pathname)
          // 跳转到首页
          router.replace('/')
        } else {
          showToast(res.data.message || '钉钉登录失败')
        }
      } catch (e) {
        showToast('钉钉登录失败')
      }
    }
  })
  </script>
  <style scoped>
  .login {
    max-width: 400px;
    margin: 40px auto;
    padding: 24px;
    background: #fff;
    border-radius: 8px;
  }
  .login-type {
    display: flex;
    justify-content: center;
    margin-bottom: 24px;
    border-bottom: 1px solid #eee;
  }
  .type-item {
    padding: 12px 24px;
    font-size: 16px;
    color: #666;
    cursor: pointer;
    position: relative;
  }
  .type-item.active {
    color: #338bff;
  }
  .type-item.active::after {
    content: '';
    position: absolute;
    bottom: -1px;
    left: 0;
    right: 0;
    height: 2px;
    background: #338bff;
  }
  .other-login {
    margin-top: 32px;
  }
  .divider {
    position: relative;
    text-align: center;
    margin: 20px 0;
  }
  .divider::before,
  .divider::after {
    content: '';
    position: absolute;
    top: 50%;
    width: calc(50% - 100px);
    height: 1px;
    background: #eee;
  }
  .divider::before {
    left: 0;
  }
  .divider::after {
    right: 0;
  }
  .divider-text {
    display: inline-block;
    padding: 0 16px;
    color: #999;
    background: #fff;
  }
  .third-party {
    display: flex;
    justify-content: center;
    gap: 32px;
    margin-top: 20px;
  }
  .third-party-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
    cursor: pointer;
  }
  .third-party-item span {
    font-size: 12px;
    color: #666;
  }
  </style>
